﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NeuralStock.Entities;
using NeuralStock.Common;
using System.IO;
using HtmlAgilityPack;
using NeuralStock.Common.WebData;

namespace NeuralStock.Tools
{
    public class GpwQuotesProvider : BaseDownloader
    {
        public List<GpwQuoteData> GetQuotesFromWeb(DateTime dateFrom, DateTime dateTo)
        {
            List<GpwQuoteData> result = new List<GpwQuoteData>();

            for (DateTime date = dateFrom; date <= dateTo; date = date.AddDays(1))
            {
                string filePath = Path.Combine(DirectoryRepository.GpwQuotesDirectory, string.Format("{0}.html", date.ToShortDateString()));
                HtmlDocument doc = DownloadAndLoad(string.Format(WebsiteRepository.GpwQuotes, date.ToShortDateString()), filePath);

                result.AddRange(RetrieveDataFromHtmlFile(doc, date));
            }

            return result;
        }

        public List<GpwQuoteData> GetQuotesFromLocal()
        {
            List<GpwQuoteData> result = new List<GpwQuoteData>();

            var files = Directory.GetFiles(DirectoryRepository.GpwQuotesDirectory);

            foreach (var file in files)
            {
                HtmlDocument doc = new HtmlDocument();
                doc.Load(file);

                string dateString = Path.GetFileNameWithoutExtension(file);
                DateTime date = DateTime.Parse(dateString);

                result.AddRange(RetrieveDataFromHtmlFile(doc, date));
            }

            return result;
        }

        private List<GpwQuoteData> RetrieveDataFromHtmlFile(HtmlDocument doc, DateTime date)
        {
            List<GpwQuoteData> results = new List<GpwQuoteData>();

            if (doc.DocumentNode.InnerText.Contains("Brak danych"))
            {
                return results;
            }

            var tableRows = doc.DocumentNode.SelectNodes("//table[@class='tab03']//tr");
            var companyQuotesTR = tableRows.Skip(3);

            foreach (var row in companyQuotesTR)
            {
                var dataRows = row.ChildNodes.Where(x => x.Name == "td").ToList();
                if (dataRows.Count >= 7)
                {
                    GpwQuoteData entity = new GpwQuoteData();
                    entity.Date = date;
                    entity.CompanyName = dataRows[0].InnerText;
                    entity.Price = ParseDecimal(dataRows[6].InnerText);
                    results.Add(entity);
                }
            }

            return results;
        }
    }
}
